﻿using System.Collections.Generic;
using Model.Entities;
using NHibernate;

namespace Model.Repositories
{
    public class Repository<T> : IRepository<T> where T : BaseEntity
    {
        #region Protected Variables

        protected ISession Session = NHibernateHelper.CurrentSession;

        #endregion
        
        #region Implementation of IRepository<T>

        public T Get(int id)
        {
            return Session.Get<T>(id);
        }

        public T Insert(T obj)
        {
            using (var transaction = Session.BeginTransaction())
            {
                Session.Save(obj);
                transaction.Commit();
            }
            return obj;
        }

        public T Update(T obj)
        {
            using (var transaction = Session.BeginTransaction())
            {
                Session.Update(obj);
                transaction.Commit();
            }
            return obj;
        }

        public void Delete(T obj)
        {
            using (var transaction = Session.BeginTransaction())
            {
                var deleted = Get(obj.Id);
                Session.Delete(deleted);
                transaction.Commit();
            }
        }

        public IList<T> GetAll()
        {
            return Session.CreateCriteria<T>().List<T>();
        }

        #endregion
    }
}
